/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ubhave.powertracker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.ubhave.powertracker.R;

import android.app.Activity;
//import android.support.v4.app.FragmentActivity;
import android.app.DialogFragment;
//import android.support.v4.app.DialogFragment;

import android.app.ExpandableListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;

//import com.ubhave.android.apis.R;


public class ViewGoalsActivity extends ExpandableListActivity implements LoginDialogListener{
//public class ViewGoalsActivity extends FragmentActivity implements LoginDialogListener{

    ExpandableListAdapter mAdapter;
    
    LifeGuideConnector lgc;
    SharedPreferences settings;
    SharedPreferences.Editor editor;
    
    String type;
    String usr;
    String intervention;
    
    PageSensorLogger psl;
    PageLogger pl;
    
    String activityPlan;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewgoals);
        
    	settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    	editor = settings.edit();
    	activityPlan = settings.getString("PAplan", "");
    	
        lgc = new LifeGuideConnector(settings);
        
        usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
        type=settings.getString("currenteatplan", "");
        
        //Handle Async Logging and Variable Retrieval
        if(settings.getBoolean("SensorsOn", false))
			psl = new PageSensorLogger(this);
        pl=new PageLogger(this);

		class AsyncLogAndRetrieve extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				//Usage Logging
		        /*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+" "+new Date()+", ");
		        editor.commit();
		        if(!usr.equals("")&&!intervention.equals(""))
		        	lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
		        else
		        	Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);*/
				
				try{
					pl.makeLog();
				
		        	//Sensor Logging
		        	if(settings.getBoolean("SensorsOn", false)){
		        		psl.makeLog();
		        	}
		        
		        	//Current eat plan variable
		        	String cepString=lgc.getVar(intervention, usr, "user", "currenteatplan",settings.getString("authkey",""));
		        	if(cepString!=null){
		        		editor.putString("currenteatplan", cepString);
		        		editor.commit();
		        		type=cepString;
		        	}
		        	
		        	//activity plan
		        	String planValue = lgc.getVar(intervention, usr, "user", "PAplan",settings.getString("authkey",""));
	        		
        			if(planValue!=null){
        				editor.putString("PAplan", planValue);
        				editor.commit();
        				activityPlan =planValue;
        			}
		        
		        	mAdapter = new MyExpandableListAdapter();
		        		        
		        	//Log.i("POWeR Tracker Special: ","Logged for Goals");
				} catch (PowerTrackerInvalidAuthKeyException e) {
					invalidKey();
				}
		        
		        return null;
			}
			
			protected void onPostExecute(Object result) {
		         asyncDone();
		    }

		};
		
		new AsyncLogAndRetrieve().execute(this);
		
        
		setPlanText();
        
    	
        //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);

		
		
        // Set up our adapter
        setListAdapter(mAdapter);
        registerForContextMenu(getExpandableListView());
       
       
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Sample menu");
      
        
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();

        String title = ((TextView) info.targetView).getText().toString();

        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
            int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
            int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition); 
            Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos,
                    Toast.LENGTH_SHORT).show();
            return true;
        } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
            int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
            Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
            return true;
        }

        return false;
    }

    /**
     * A simple adapter which maintains an ArrayList of photo resource Ids. 
     * Each photo is displayed as an image. This adapter supports clearing the
     * list of photos and adding a new photo.
     *
     */
    public class MyExpandableListAdapter extends BaseExpandableListAdapter {
   	
    	Resources res = getResources();
    	
    	boolean[] goalcheck = new boolean[7];    	
    	ArrayList<String> groups = populateGroups();
    	ArrayList<String> children = populateChildren();
    	
    	
    	public ArrayList<String> populateGroups(){
    		
    		ArrayList<String> groupsRes = new ArrayList<String>();
    		
    		String usr = settings.getString("LifeGuideUser", "");
    		String intervention = settings.getString("LifeGuideInterventionId", "");
    		
    		ConnectivityManager cm = (ConnectivityManager)PowerTrackerApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    		NetworkInfo ni = cm.getActiveNetworkInfo();
    		
    		try{
    			for(int i=1;i<4;i++){
            		String candidateGoal = lgc.getVar(intervention, usr, "user", "currentgoal"+i,settings.getString("authkey",""));
            	
            		if(candidateGoal!=null)
            			editor.putString("currentgoal"+i, candidateGoal);
            		else if(ni!=null)
            			editor.putString("currentgoal"+i, "");
            		editor.commit();
            	
            		//if(candidateGoal!=null){
            		if(!settings.getString("currentgoal"+i, "").equals("")){
            		           		
            			groupsRes.add("Eating Goal: "+settings.getString("currentgoal"+i, ""));
            			//groupsRes.add("Eating Goal: "+candidateGoal);
            		            		
            			goalcheck[i-1]=true;
            		}
            		else
            			goalcheck[i-1]=false;
        		}
    		
    			
    			if(!activityPlan.equals("walk")){
	    			for(int i=1;i<4;i++){
	    				String candidateGoal = lgc.getVar(intervention, usr, "user", "currentpagoal"+i,settings.getString("authkey",""));
	    			    			
	            		if(candidateGoal!=null)
	            			editor.putString("currentpagoal"+i, candidateGoal);
	            		else if(ni!=null)
	            			editor.putString("currentpagoal"+i, "");
	            		editor.commit();
	            	
	    				//if(candidateGoal!=null){
	    				if(!settings.getString("currentpagoal"+i, "").equals("")){
	    					
	    					groupsRes.add("Activity Goal: "+settings.getString("currentpagoal"+i, ""));
	            			//groupsRes.add("Activity Goal: "+candidateGoal);
	            			goalcheck[i+2]=true;
	            		}
	            		else
	            			goalcheck[i+2]=false;
	        		}
    			}
    			else {
    			
	    			//Check for steps goal
	    			String candidateGoal = lgc.getVar(intervention, usr, "user", "currentsteps",settings.getString("authkey",""));
	    			
	        		if(candidateGoal!=null)
	        			editor.putString("currentsteps", candidateGoal);
	        		else if(ni!=null)
	        			editor.putString("currentsteps", "");
	        		editor.commit();
	        	
					if(!settings.getString("currentsteps", "").equals("")){
						
						groupsRes.add("Steps Goal: "+settings.getString("currentsteps", ""));
	        			goalcheck[6]=true;
	        		}
	        		else
	        			goalcheck[6]=false;
    			}
    			
    			
    			
    		} catch (PowerTrackerInvalidAuthKeyException e) {
    			invalidKey();
    		}
    		
    		return groupsRes;
    	}
    	
    	
    	public ArrayList<String> populateChildren(){
    		
    		ArrayList<String> childrenRes = new ArrayList<String>();
    		
    		String usr = settings.getString("LifeGuideUser", "");
    		String intervention = settings.getString("LifeGuideInterventionId", "");
    		
    		ConnectivityManager cm = (ConnectivityManager)PowerTrackerApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    		NetworkInfo ni = cm.getActiveNetworkInfo();
    		
    		try{
    			for(int i=1;i<4;i++){
    				String candidatePlan = lgc.getVar(intervention, usr, "user", "currentplan"+i,settings.getString("authkey",""));
            		if(candidatePlan!=null)
            			editor.putString("currentplan"+i, candidatePlan);
            		else if(ni!=null)
            			editor.putString("currentplan"+i, "");
            	
            	
            		editor.commit();
            	
    				if(settings.getString("currentplan"+i, "")!=null&&goalcheck[i-1]){      
            		
    					childrenRes.add(settings.getString("currentplan"+i, ""));    
    					//childrenRes.add(candidatePlan);            		
            		}
        		}
    		
    			//This is a hack because PA goals don't have plans.
    			while(groups.size()>childrenRes.size()){
    				childrenRes.add("");
    			}
    		} catch (PowerTrackerInvalidAuthKeyException e) {
    			invalidKey();
    		}
    		
    		return childrenRes;
    	}
    	
        public Object getChild(int groupPosition, int childPosition) {
            //return children[groupPosition][childPosition];
        	return children.get(groupPosition);
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        public int getChildrenCount(int groupPosition) {
            //return children[groupPosition].length;
        	return 1;
        }

        public TextView getChildGenericView() {
                   	
        	// Layout parameters for the ExpandableListView
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            TextView textView = new TextView(ViewGoalsActivity.this);
            textView.setLayoutParams(lp);
            // Center the text vertically
            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            // Set the text starting position
                        
            textView.setPadding(36, 20, 0, 20);
            return textView;
        }
        
        public TextView getGroupGenericView() {
            
        	// Layout parameters for the ExpandableListView
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            
            

            TextView textView = new TextView(ViewGoalsActivity.this);
            textView.setLayoutParams(lp);
            
            
            // Center the text vertically
            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            // Set the text starting position
                       
            textView.setPadding(36, 20, 0, 20);
            return textView;
        }

        public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                View convertView, ViewGroup parent) {
                   	
        	TextView textView = getChildGenericView();
            
            textView.setText(getChild(groupPosition, childPosition).toString());
            return textView;
        }

        public Object getGroup(int groupPosition) {
        	return groups.get(groupPosition);
        	//return groups[groupPosition];
        }

        public int getGroupCount() {
            return groups.size();
        	//return groups.length;
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
                ViewGroup parent) {
            
        	TextView textView = getGroupGenericView();
            textView.setText(getGroup(groupPosition).toString());
            return textView;
        }

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public boolean hasStableIds() {
            return true;
        }
                
    }
    
    public void goDailyGoalUpdate(View v){
    	
    	String lastUpdate=settings.getString("lastDailyUpdate", "");
    	Date tempDate = new Date();
    	String now = tempDate.getDate()+"-"+tempDate.getMonth()+"-"+tempDate.getYear();
    	
    	//check to see if an update was made yet today. Setting OR boolean to true overides this check.
    	if(!lastUpdate.equals(now)||!settings.getBoolean("DailyUpdateInhibitorOn", true)){
    		Intent myIntent = new Intent().setClass(this, DailyGoalUpdateActivity.class);
            startActivityForResult(myIntent, 0);
    	}
    	else{
    		Toast.makeText(this, getResources().getString(R.string.multipleUpdateInhibitorError), Toast.LENGTH_SHORT).show();
    	}
    	
    }
    
    public void goRedFoodList(View v){
    	
    	Intent myIntent = new Intent().setClass(this, FoodListActivity.class);
    	myIntent.putExtra("list", "Red");
        startActivityForResult(myIntent, 0);
    	
    }

    public void goAmberFoodList(View v){
	
    	Intent myIntent = new Intent().setClass(this, FoodListActivity.class);
    	myIntent.putExtra("list", "Amber");
    	startActivityForResult(myIntent, 0);
	
    }
    
    public void goGreenFoodList(View v){
    	
    	Intent myIntent = new Intent().setClass(this, FoodListActivity.class);
    	myIntent.putExtra("list", "Green");
        startActivityForResult(myIntent, 0);
    	
    }
    
    public void asyncDone(){
    	
    	setPlanText();
    	
    	setListAdapter(mAdapter);
        registerForContextMenu(getExpandableListView());
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(psl!=null)
        	psl.resumeLocationSensing();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        	
    	switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                goHome();
                return true;
            case R.id.home:
                // app icon in options clicked; go home
            	goHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.o_menu, menu);
        return true;
    }
    
    public void setPlanText(){
    	if(type.equals("cal")){
			TextView fltitletv = (TextView) findViewById(R.id.VGFoodListTitle);
			fltitletv.setText("Food lists by amount of calories");
			TextView ptexttv = (TextView) findViewById(R.id.VGPlanText);
			ptexttv.setText("You are on the low calories plan");
		}
		else if(type.equals("carb")){
			TextView fltitletv = (TextView) findViewById(R.id.VGFoodListTitle);
			fltitletv.setText("Food lists by amount of carbohydrates");
			TextView ptexttv = (TextView) findViewById(R.id.VGPlanText);
			ptexttv.setText("You are on the low carbohydrates plan");
		}
    }
    
    public void goHome(){
    	Intent intent = new Intent(this, PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    public void invalidKey(){
		//DialogFragment dialog = new LoginDialog();
		Bundle errorBundle = new Bundle();
	    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
	    //dialog.setArguments(errorBundle);
	    //dialog.show(this.getFragmentManager(), "LoginDialog");
	    
	    goHome();
	}
    
  	@Override
	public void onLoginDialogPositiveClick() {
		// TODO Auto-generated method stub
  		Log.i("POWeR Tracker Special: ","Clicked OK");
  		finish();
  		startActivity(getIntent());
	}


	@Override
	public void onLoginDialogNegativeClick() {
		// TODO Auto-generated method stub
		Log.i("POWeR Tracker Special: ","Clicked Cancel");
		goHome();
	}
    
}